<template>
  <div class="device-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>设备管理</h2>
      <p>新增设备及查看设备列表（支持阈值预设、设备删除）</p>
    </div>

    <!-- 新增设备表单 -->
    <div class="add-device-card">
      <h3>📱 新增设备</h3>
      <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="150px">
        <!-- 设备名称 -->
        <el-form-item label="设备名称" prop="name">
          <el-input
              v-model="addForm.name"
              placeholder="请输入自定义设备名称（如：书房传感器）"
              maxLength="30"
          ></el-input>
        </el-form-item>

        <!-- 应用场景 -->
        <el-form-item label="应用场景" prop="scene">
          <el-select
              v-model="addForm.scene"
              placeholder="请选择设备应用场景"
          >
            <el-option label="智慧鱼塘" value="fishpond"></el-option>
            <el-option label="智慧家居" value="home"></el-option>
            <el-option label="智慧种植" value="plantation"></el-option>
            <el-option label="智慧猪舍" value="pigsty"></el-option>
          </el-select>
        </el-form-item>

        <!-- 阈值预设区域（可空，不强制填写） -->
        <el-form-item label="阈值预设" class="threshold-group">
          <div class="threshold-row">
            <!-- 温度阈值 -->
            <el-form-item label="温度阈值(℃)" prop="temperatureThreshold">
              <el-input
                  v-model.number="addForm.temperatureThreshold"
                  placeholder="请输入温度阈值（可选）"
                  type="number"
                  step="0.1"
              ></el-input>
            </el-form-item>

            <!-- 土壤湿度阈值 -->
            <el-form-item label="土壤湿度阈值(%)" prop="soilMoistureThreshold">
              <el-input
                  v-model.number="addForm.soilMoistureThreshold"
                  placeholder="请输入土壤湿度阈值（可选）"
                  type="number"
                  step="0.1"
                  min="0"
                  max="100"
              ></el-input>
            </el-form-item>
          </div>

          <div class="threshold-row">
            <!-- 一氧化碳浓度阈值 -->
            <el-form-item label="一氧化碳阈值(ppm)" prop="carbonMonoxideThreshold">
              <el-input
                  v-model.number="addForm.carbonMonoxideThreshold"
                  placeholder="请输入一氧化碳浓度阈值（可选）"
                  type="number"
                  step="0.01"
                  min="0"
              ></el-input>
            </el-form-item>
          </div>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button
              type="primary"
              @click="handleAddDevice"
              :loading="isSubmitting"
          >
            确认新增
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 设备列表展示（增加阈值列、删除操作列） -->
    <div class="device-list-card">
      <h3>📋 设备列表</h3>
      <el-table
          :data="deviceList"
          border
          stripe
          style="width: 100%"
          v-loading="isLoading"
          element-loading-text="加载设备数据中..."
          empty-text="暂无设备数据"
      >
        <el-table-column
            label="设备ID"
            prop="id"
            align="center"
            width="100"
        ></el-table-column>
        <el-table-column
            label="设备名称"
            prop="name"
            align="center"
            width="180"
        ></el-table-column>
        <el-table-column
            label="应用场景"
            prop="scene"
            align="center"
            width="150"
        >
          <template #default="scope">
            <span v-if="scope.row.scene === 'fishpond'">智慧鱼塘</span>
            <span v-else-if="scope.row.scene === 'home'">智慧家居</span>
            <span v-else-if="scope.row.scene === 'plantation'">智慧种植</span>
            <span v-else-if="scope.row.scene === 'pigsty'">智慧猪舍</span>
            <span v-else>未知场景</span>
          </template>
        </el-table-column>
        <el-table-column
            label="温度阈值(℃)"
            prop="temperatureThreshold"
            align="center"
            width="150"
        >
          <template #default="scope">
            {{ scope.row.temperatureThreshold ?? '未设置' }}
          </template>
        </el-table-column>
        <el-table-column
            label="土壤湿度阈值(%)"
            prop="soilMoistureThreshold"
            align="center"
            width="160"
        >
          <template #default="scope">
            {{ scope.row.soilMoistureThreshold ?? '未设置' }}
          </template>
        </el-table-column>
        <el-table-column
            label="一氧化碳阈值(ppm)"
            prop="carbonMonoxideThreshold"
            align="center"
            width="180"
        >
          <template #default="scope">
            {{ scope.row.carbonMonoxideThreshold ?? '未设置' }}
          </template>
        </el-table-column>
        <el-table-column
            label="关联用户ID"
            prop="userId"
            align="center"
            width="120"
        ></el-table-column>
        <el-table-column
            label="操作"
            align="center"
            width="120"
        >
          <template #default="scope">
            <el-button
                type="danger"
                size="small"
                @click="handleDeleteDevice(scope.row.id)"
                :loading="scope.row.isDeleting"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { deviceAPI } from '@/api/deviceAPI'

// 表单相关
const addFormRef = ref(null)
const isSubmitting = ref(false)
const addForm = ref({
  name: '',
  scene: '',
  userId: 999, // 固定设置为999
  temperatureThreshold: null,
  soilMoistureThreshold: null,
  carbonMonoxideThreshold: null
})

// 表单校验规则
const addRules = ref({
  name: [
    { required: true, message: '请输入设备名称', trigger: 'blur' },
    { max: 30, message: '设备名称长度不能超过30个字符', trigger: 'blur' }
  ],
  scene: [
    { required: true, message: '请选择应用场景', trigger: 'change' }
  ],
  temperatureThreshold: [
    { type: 'number', message: '请输入有效的数字', trigger: 'blur', required: false }
  ],
  soilMoistureThreshold: [
    { type: 'number', message: '请输入有效的数字', trigger: 'blur', required: false },
    { min: 0, max: 100, message: '土壤湿度阈值范围为0-100', trigger: 'blur' }
  ],
  carbonMonoxideThreshold: [
    { type: 'number', message: '请输入有效的数字', trigger: 'blur', required: false },
    { min: 0, message: '一氧化碳浓度阈值不能为负数', trigger: 'blur' }
  ]
})

// 设备列表相关
const deviceList = ref([])
const isLoading = ref(false)

// 页面加载时查询设备列表（用999查）
onMounted(() => {
  getDeviceList()
})

/**
 * 新增设备提交
 */
const handleAddDevice = async () => {
  // 表单校验
  await addFormRef.value.validate().catch(err => {
    console.error('表单校验失败：', err)
    return
  })

  try {
    isSubmitting.value = true
    const res = await deviceAPI.addDevice(addForm.value)
    if (res) {
      ElMessage.success('设备新增成功！')
      addFormRef.value.resetFields()
      // 重置后重新给userId赋值999
      addForm.value.userId = 999
      getDeviceList()
    } else {
      ElMessage.error('设备新增失败，请重试')
    }
  } catch (error) {
    console.error('新增设备接口异常：', error)
    ElMessage.error('网络异常，新增设备失败')
  } finally {
    isSubmitting.value = false
  }
}

/**
 * 查询设备列表
 */
const getDeviceList = async () => {
  const userId = 999; // 固定用999查询
  console.log('查询设备列表：userId=', userId)

  try {
    isLoading.value = true
    const res = await deviceAPI.getDevicesByUserId(userId)
    console.log('设备列表查询结果（含阈值）：', res)
    // 给每个设备添加删除加载状态字段
    deviceList.value = res.map(item => ({ ...item, isDeleting: false }))
  } catch (error) {
    console.error('查询设备列表失败：', error)
    ElMessage.error('查询设备列表失败，请重试')
    deviceList.value = []
  } finally {
    isLoading.value = false
  }
}

/**
 * 删除设备
 * @param {number} id - 设备ID
 */
const handleDeleteDevice = async (id) => {
  // 确认删除对话框
  ElMessageBox.confirm(
      '此操作将永久删除该设备，是否继续？',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    // 找到当前设备，设置删除加载状态
    const deviceIndex = deviceList.value.findIndex(item => item.id === id)
    if (deviceIndex === -1) return

    deviceList.value[deviceIndex].isDeleting = true

    try {
      // 调用删除接口
      const res = await deviceAPI.deleteDeviceById(id)
      if (res) {
        ElMessage.success('设备删除成功！')
        // 重新查询设备列表
        getDeviceList()
      } else {
        ElMessage.error('设备删除失败，请重试')
        // 恢复删除加载状态
        deviceList.value[deviceIndex].isDeleting = false
      }
    } catch (error) {
      console.error('删除设备接口异常：', error)
      ElMessage.error('网络异常，删除设备失败')
      // 恢复删除加载状态
      deviceList.value[deviceIndex].isDeleting = false
    }
  }).catch(() => {
    // 取消删除
    ElMessage.info('已取消删除操作')
  })
}
</script>

<style scoped>
.device-management {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.page-header {
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.page-header h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 1.4rem;
  font-weight: 600;
}

.page-header p {
  margin: 5px 0 0 0;
  color: #6c757d;
  font-size: 0.9rem;
}

.add-device-card {
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.add-device-card h3 {
  margin: 0 0 20px 0;
  color: #2c3e50;
  font-size: 1.1rem;
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 阈值表单样式 */
.threshold-group {
  margin-top: 10px;
}

.threshold-row {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.threshold-row .el-form-item {
  flex: 1;
  min-width: 200px;
}

.device-list-card {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.device-list-card h3 {
  margin: 0 0 20px 0;
  color: #2c3e50;
  font-size: 1.1rem;
  display: flex;
  align-items: center;
  gap: 8px;
}

.el-table {
  margin-bottom: 15px;
  background: #fff;
}

/* 适配小屏幕 */
@media (max-width: 1200px) {
  .threshold-row {
    gap: 15px;
  }
}

@media (max-width: 768px) {
  .threshold-row {
    flex-direction: column;
    gap: 10px;
  }
  /* 操作列适配 */
  .el-table-column[label="操作"] {
    width: 100px !important;
  }
  /* 缩小部分列宽适配 */
  .el-table-column[label="设备名称"] {
    width: 140px !important;
  }
  .el-table-column[label="一氧化碳阈值(ppm)"] {
    width: 140px !important;
  }
}

.no-data {
  text-align: center;
  padding: 40px 0;
  color: #6c757d;
  font-size: 0.95rem;
}

/* 删除按钮样式优化 */
.el-button--danger.is-small {
  padding: 6px 12px;
}
</style>